/**
  ******************************************************************************
  * @file    usart.c
  * @brief   This file provides code for the configuration
  *          of the USART instances.
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "usart.h"


#if SYSTEM_SUPPORT_OS
#include "includes.h"
#endif


#if EN_USART1_RX

u8 USART_RX_BUF[USART_REC_LEN];
u16 USART_RX_STA = 0;

u8 aRxBuffer[RXBUFFERSIZE];
extern UART_HandleTypeDef huart1;


//void MX_UART1_Init(u32 bound) {
//    huart1.Instance = USART1;
//    huart1.Init.BaudRate = bound;
//    huart1.Init.WordLength = UART_WORDLENGTH_8B;
//    huart1.Init.StopBits = UART_STOPBITS_1;
//    huart1.Init.Parity = UART_PARITY_NONE;
//    huart1.Init.Mode = UART_MODE_TX_RX;
//    huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
//    huart1.Init.OverSampling = UART_OVERSAMPLING_16;
//    HAL_UART_Init(&huart1);
//    //开启接收中断，标记位UART_IT_RXNE ， 并设置接收缓冲以及接收缓冲最大数据量
//    HAL_UART_Receive_IT(&huart1, (u8 *) aRxBuffer, RXBUFFERSIZE);
//}


/**
 * 中断回调函数
 * @param huart
 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
    //如果是串口1
    if (huart->Instance == USART1) {
        //接收未完成
        if ((USART_RX_STA & 0x8000) == 0) {
            if (USART_RX_STA & 0x4000) {
                //接收到0x0d
                if (aRxBuffer[0] != 0x0a)USART_RX_STA = 0;//接收错误，重新开始
                else USART_RX_STA |= 0x8000;//接收完成
            } else {//还没接收0x0D
                if (aRxBuffer[0] == 0x0d)USART_RX_STA |= 0x4000;
                else {
                    USART_RX_BUF[USART_RX_STA & 0X3FFF] = aRxBuffer[0];
                    USART_RX_STA++;
                    if (USART_RX_STA > (USART_REC_LEN - 1))USART_RX_STA = 0;//接收到错误数据，重新开始
                }
            }
        }

    }
}

//中断服务函数
void USART1_IRQHandler(void) {
    u32 timeout = 0;
#if SYSTEM_SUPPORT_OS
    OSIntEnter();
#endif

    HAL_UART_IRQHandler(&huart1);

    timeout = 0;
    while (HAL_UART_GetState(&huart1) != HAL_UART_STATE_READY) {
        timeout++;
        if (timeout > HAL_MAX_DELAY) break;

    }

    timeout = 0;
    while (HAL_UART_Receive_IT(&huart1, (u8 *) aRxBuffer, RXBUFFERSIZE) != HAL_OK) {
        timeout++;
        if (timeout > HAL_MAX_DELAY) break;
    }
#if SYSTEM_SUPPORT_OS
    OSIntExit();
#endif
}

#endif

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
